package com.selune.online.ordering.system.common.cors;

import java.util.List;
import java.util.Objects;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.DefaultCorsProcessor;

/**
 * Created with IntelliJ IDEA.
 *
 * @author xiaoyp
 * @date 2020/3/24
 * <p>
 * Description:
 */
public class MyCorsProcessor extends DefaultCorsProcessor {
	
	public static final String ALL = "*";
	
	@Override
	public String checkOrigin(CorsConfiguration config, String requestOrigin) {
		List<String> allowedOrigins = config.getAllowedOrigins();
		Boolean allowCredentials = config.getAllowCredentials();
		if (!StringUtils.hasText(requestOrigin)) {
			return null;
		}
		if (ObjectUtils.isEmpty(allowedOrigins)) {
			return null;
		}
		
		if (allowedOrigins.contains(ALL)) {
			if (!Objects.equals(allowCredentials, Boolean.TRUE)) {
				return ALL;
			}
			else {
				return requestOrigin;
			}
		}
		for (String allowedOrigin : allowedOrigins) {
			if (requestOrigin.endsWith(allowedOrigin.replace("*", ""))) {
				return requestOrigin;
			}
		}
		
		return null;
	}
}
